<template>
  <qx-table :option="tableOption" :remoteData="remoteData">
    <template v-if="!nonSearch" v-slot:top>
      <qx-form v-model="searchForm" :option="searchOption" isSearch @submit="startSearch"></qx-form>
    </template>
    <template v-if="!nonSearch" v-slot:menuLeft>
      <q-btn color="primary" icon="add" unelevated @click="handleCreate">
        {{ $t('Add') }}
      </q-btn>
      <q-btn outline text-color="primary" @click="handleSyncRCS">
        {{ $t('Misc.SynchronizeRCSData') }}
      </q-btn>
      <q-btn outline text-color="primary" @click="handleRefresh">
        {{ $t('Misc.RefreshCache') }}
      </q-btn>
    </template>
    <template v-slot:Image="{ row }">
      <div class="full-width row justify-center">
        <div class="row full-width text-dark text-weight-medium text-body1">
          <div>{{ getLabelByValue(row.agvBrandCode, AGVBrands, brandProps) }}</div>
          <q-space></q-space>
          <div>{{ row.agvDeviceTypeName || '' }}</div>
        </div>
        <AMRIMG :amrType="row.agvTypeCode" :imageUrl="row.imageUrl" @click="handlePortrait(row)"></AMRIMG>
        <div class="row full-width text-dark text-weight-medium text-body1">
          <div>{{ row.agvBuyDate ? date.formatDate(row.agvBuyDate, 'YYYY-MM-DD') : '' }}</div>
          <q-space></q-space>
          <div class="row no-wrap items-center q-gutter-sm text-body1">
            <q-icon :color="row.agvDeviceNavigationType === '0' ? 'primary' : 'grey-5'" name="qr_code"></q-icon>
            <q-icon :color="row.agvDeviceNavigationType === '3' ? 'primary' : 'grey-5'" name="view_in_ar"></q-icon>
            <q-icon :color="row.agvDeviceNavigationType === '4' ? 'primary' : 'grey-5'" class="rotate-135"
                    name="straighten"></q-icon>
            <q-icon :color="row.agvDeviceNavigationType === '1' ? 'primary' : 'grey-5'" name="flare"></q-icon>
            <div :class="row.agvDeviceNavigationType === '2' ? 'text-primary' : 'text-grey-5'" class="text-no-wrap">
              slam
            </div>
          </div>
        </div>
        <q-separator class="full-width q-my-sm"></q-separator>
        <div class="full-width row justify-between items-center">
          <q-badge color="primary" outline>230H</q-badge>
          <q-badge color="primary" outline>30KM</q-badge>
          <q-badge color="positive" outline>
            <q-icon name="miscellaneous_services"></q-icon>
            88%
          </q-badge>
          <q-badge color="negative" outline>
            <q-icon name="handyman" />
            12%
          </q-badge>
        </div>
      </div>
    </template>
    <template v-if="!nonSearch" v-slot:menu="{ row }">
      <q-btn class="col" color="primary" icon="mdi-square-edit-outline" outline unelevated @click="handleUpdate(row)">
        {{ $t('Edit') }}
      </q-btn>
      <q-btn class="col" color="primary" icon="delete" outline unelevated @click="handleDelete(row)">
        {{ $t('Del') }}
      </q-btn>
    </template>
  </qx-table>
  <q-modal v-model="modalVisible" :header="formInfo.id ? $t('Edit') : $t('Add')" :width="500" btnAlign="center"
           position="right" @beforeClose="beforeClose" @confirm="submitForm">
    <qx-form ref="FormRef" v-model="formInfo" :option="tableOption"></qx-form>
  </q-modal>
  <q-modal v-model="syncModelVisible" :header="$t('Misc.SynchronizeRCSData')" width="400" @beforeClose="beforeClose"
           @confirm="submitSync">
    <qx-form ref="FormRef" v-model="formInfo" :option="syncOption"></qx-form>
  </q-modal>
  <AGVPortrait v-model="portraitVisible" :rowInfo="formInfo"></AGVPortrait>
</template>
<script setup>
import { i18n, toI18nName } from 'boot/i18n.js'
import { date, Notify } from 'quasar'
import { deleteAPI, postAPI, putAPI } from 'src/api/index.js'
import { getRemoteData, setRemoteData } from 'src/enum/ajaxRemoteData.js'
import { enableOrDisable, NavigationTypes } from 'src/enum/index.js'
import AGVPortrait from 'src/views/AGVCore/AGVPortrait.vue'
import AMRIMG from 'src/views/AGVCore/AMRIMG.vue'
import { computed, onMounted, ref } from 'vue'
import { createDialog, deepClone, getLabelByValue } from 'src/utils/utils.js'

defineProps({ nonSearch: Boolean })

const formInfo = ref({})
const FormRef = ref(null)
const AGVBrands = ref([])
const AGVModels = ref([])
const searchForm = ref({})
const modalVisible = ref(false)
const portraitVisible = ref(false)
const syncModelVisible = ref(false)
const remoteData = ref({ dicUrl: '/yfagv/api/agvManage/list' })
getRemoteData('agv_brand', '/yfagv/api/agvCfgBrand/list').then(data => (AGVBrands.value = data))
getRemoteData('agv_model', '/yfagv/api/agvTypeDevice/list').then(data => (AGVModels.value = data))
const AGVStatus = computed(() => [...enableOrDisable.value, { label: i18n.t('Scrap'), value: '2', color: 'red' }])
const brandProps = computed(() => ({ label: `${toI18nName('agvBrandNameZhCn')}`, value: 'agvBrandCode' }))
const filterAGVModels = computed(() => AGVModels.value.filter(el => el.agvBrandCode === formInfo.value.agvBrandCode))
const syncOption = computed(() => {
  return {
    span: 22, labelWidth: 90,
    column: [{
      label: `${i18n.t('AGVCore.AGVBrand')}`, field: 'agvBrandCode', type: 'select', options: AGVBrands.value,
      props: brandProps.value, required: true
    }]
  }
})
const searchOption = computed(() => {
  return {
    searchSpan: 5, searchLabelWidth: 70,
    column: [{
      label: `${i18n.t('AGVCore.AGVCode')}`, field: 'agvDeviceCode'
    }, {
      label: `${i18n.t('AGVCore.AGVBrand')}`, field: 'agvBrandCode', type: 'select', options: AGVBrands.value,
      props: brandProps.value
    }, {
      label: `${i18n.t('AGVCore.AGVModel')}`, field: 'agvDeviceTypeCode', type: 'select',
      options: AGVModels.value, props: { label: 'deviceName', value: 'deviceCode' }
    }, {
      label: `${i18n.t('AGVCore.AGVStatus')}`, field: 'status', type: 'select', options: AGVStatus.value
    }]
  }
})
const tableOption = computed(() => {
  return {
    grid: true, span: 22, export: true, labelWidth: 100,
    column: [{
      label: `${i18n.t('AGVCore.AGVCode')}`, field: 'agvDeviceCode', minWidth: 100, required: true,
      readonly: !!formInfo.value.id, topLeft: true
    }, {
      label: `${i18n.t('AGVCore.AGVBrand')}`, field: 'agvBrandCode', type: 'select', options: AGVBrands.value,
      hide: true, minWidth: 100, props: brandProps.value, required: true,
      change: () => formInfo.value.agvDeviceTypeCode = ''
    }, {
      label: `${i18n.t('AGVCore.AGVModel')}`, field: 'agvDeviceTypeCode', type: 'select', required: true,
      options: filterAGVModels.value, minWidth: 100, hide: true, props: { label: 'deviceName', value: 'deviceCode' }
    }, {
      label: '', field: 'Image', slot: true, export: false, minWidth: 100, search: false, nonHeader: true,
      display: false, showInfo: false
    }, {
      label: `${i18n.t('Misc.PurchaseDate')}`, field: 'agvBuyDate', type: 'date', required: true, minWidth: 70,
      format: val => val ? date.formatDate(val, 'YYYY-MM-DD') : '', hide: true
    }, {
      label: `${i18n.t('AGVCore.NavigationType')}`, field: 'agvDeviceNavigationType', type: 'radio', value: '0',
      required: true, options: NavigationTypes.value, minWidth: 70, hide: true
    }, {
      label: `${i18n.t('AGVCore.AGVStatus')}`, field: 'status', type: 'radio', options: AGVStatus.value, value: '1',
      required: true, topRight: true, useTag: true, minWidth: 80
    }]
  }
})

const handleCreate = () => {
  modalVisible.value = true
}
const handlePortrait = row => {
  formInfo.value = row
  portraitVisible.value = true
}
const handleUpdate = row => {
  formInfo.value = deepClone(row)
  if (row.agvBuyDate) formInfo.value.agvBuyDate = date.formatDate(row.agvBuyDate, 'YYYY-MM-DD')
  modalVisible.value = true
}
const handleSyncRCS = () => {
  createDialog({ msg: `${i18n.t('Misc.SyncTip1')}` }, () => {
    syncModelVisible.value = true
  }, () => {})
}
const handleRefresh = () => {
  const msg = `${i18n.t('Misc.RefreshCacheTips', { name: 'AGV' })}`
  createDialog({ msg }, () => {
    postAPI('/yfagv/api/agvManage/flushAgvListCache', {}, () => {
      Notify.create({ type: 'positive', message: `${i18n.t('Misc.RefreshCacheSuccess')}` })
      startSearch()
    })
  }, () => {})
}
const handleDelete = row => {
  createDialog({ msg: `${i18n.t('DelTips')}` }, () => {
    deleteAPI(`/yfagv/api/agvManage/${row.id}`, {}, () => startSearch('clear'))
  }, () => {})
}
const formatSearchForm = () => ({ ...searchForm.value })
const startSearch = (action, done) => {
  remoteData.value.params = formatSearchForm()
  remoteData.value.clearSelected = true
  if (done) done()
  action === 'clear' && setRemoteData('agv_amr')
}
const beforeClose = () => {
  if (FormRef.value) FormRef.value.onReset()
  modalVisible.value = false
  syncModelVisible.value = false
}
const submitForm = mDone => {
  FormRef.value.validate((form, done) => {
    const API = form.id ? putAPI : postAPI
    form.agvDeviceName = form.agvDeviceCode
    API('/yfagv/api/agvManage', form, () => {
      startSearch('clear')
      done()
      mDone && mDone()
    }, () => {
      done()
      mDone && mDone(false)
    })
  }, () => mDone && mDone(false))
}
const submitSync = mDone => {
  FormRef.value.validate((form, done) => {
    postAPI('/yfagv/api/syncRcsToFactoryApi/syncAgvManage', form, () => {
      startSearch('clear')
      done()
      mDone && mDone()
    }, () => {
      done()
      mDone && mDone(false)
    })
  }, () => mDone && mDone(false))
}

onMounted(startSearch)
</script>